package com.bgs.travelapp.util;

import com.bgs.travelapp.order.entity.ScenicOrderEntity;
import com.bgs.travelapp.order.mapper.PurchaseMapper;
import com.bgs.travelapp.ticket.mapper.TicketMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * @author lzy
 * @auther zcy fys
 * @date 2022/8/10 14:41
 */
@Component
@Transactional
public class RedisKeyExpirationListener  extends KeyExpirationEventMessageListener {

    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    @Resource
    PurchaseMapper purchaseMapper;

    @Resource
    TicketMapper ticketMapper;

    @Autowired
    RedisUtil redisUtil;

    /**
     * 监听redis过期key
     * @param message
     * @param pattern
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {
        String orderCode = message.toString();
        ScenicOrderEntity scenicEntity = new ScenicOrderEntity();
        scenicEntity.setOrderNo(orderCode);
        ScenicOrderEntity scenicOrderEntity = purchaseMapper.selectOne(scenicEntity);
        // 订单状态 4为：已取消
        Integer orderStatus = 4;
        // 订单未支付，支付超时，修改该订单状态为：已取消
        purchaseMapper.updateOrderStatus(orderCode,orderStatus);
        // 获取订单购买的景区 Id
        Integer scenicId = scenicOrderEntity.getScenicId();
        // 获取该订单购买的票数
        Integer ticketNum = scenicOrderEntity.getTicketNum();
        // 将订单购买的景区门票的票数恢复
        ticketMapper.UpdateTicketsin(scenicId,ticketNum);
    }
}
